<template>
  <!-- MemberSet 会员设置 -->
  <PageContainer>
    <view class="container">
      <Header title="会员设置" />
      <BasicsForm
        @register="formRegister"
        @submit="onSubmit"
        :show-placeholder-view="false"
        @on-schema-change="onChange"
      >
        <template #dynamicSlot="{ field, model }">
          <view class="integrity">
            <view class="_label">资料完整度</view>
            <view class="_value">
              <view class="-num">{{ info?.dataIntegrity || 0 }}%</view>
              <button class="-share" open-type="share">邀请完善</button>
            </view>
          </view>
        </template>
      </BasicsForm>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  MemberSet  会员设置 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { settingInfo, updateSettingInfo } from '@/api/admin';
  import { memberServiceList, memberGroupList } from '@/api/member';
  import { onLoad } from '@/router';
  import { onMounted, ref } from 'vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import type { ISettingInfoResData, IUpdateSettingInfoData } from '@/api/admin/types';
  import { memberTypeGetList } from '@/api/membership';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { Toast } from '@/utils';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { onShareAppMessage } from '@dcloudio/uni-app';
  import type { OnchangeArgument } from '@/components/Form/types';
  import dayjs from 'dayjs';
import { useAppShare } from '@/hooks/core/useAppShare';

  const { setWxSharePath } = useAppShare()

  const info = ref<ISettingInfoResData>();

  const [register, { getFieldsValue, setFieldsValue, updateSchema, appendSchemaByField }] = useForm(
    {
      labelAlign: 'left',
      validateTrigger: 'bind',
      schemas: [],
      btnGroupOptions: {
        submit: { text: '提交' },
      },
    },
  );

  const editData = ref<FormData>();

  function formRegister(instance: FormActionType) {
    register(instance);
    // editData.value && setFieldsValue(editData.value);
  }

  const id = ref<number>();
  const getSettingInfo = async () => {
    try {
      if (!id.value) return;
      let res = await settingInfo(id.value);
      info.value = res;

      const fields: FormSchema[] = [
        {
          field: 'memberName',
          label: '会员名称',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: info.value?.memberName,
        },
        {
          field: 'levelId',
          label: '会员职务',
          component: 'Select',
          required: true,
          defaultValue: info.value?.levelId,
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'attacheUserId',
          label: '服务专员',
          component: 'Select',
          defaultValue: info.value?.attacheUserId || '',
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'joinTime',
          label: '入会时间',
          component: 'DatePicker',
          required: true,
          defaultValue: info.value?.joinTime,
        },
        {
          field: 'memberEndTime',
          label: '到期时间',
          component: 'DatePicker',
          required: true,
          defaultValue: info.value?.memberEndTime,
          isOnChange: true,
        },
        {
          field: 'companyShow',
          label: '单位在单位列表展示',
          component: 'Switch',
          defaultValue: info.value?.companyShow === 1,
        },
        {
          field: 'leadingShow',
          label: '负责人在人脉列表展示',
          component: 'Switch',
          defaultValue: info.value?.leadingShow === 1,
        },
        // {
        //   field: 'show',
        //   label: '对外公开',
        //   component: 'Switch',
        //   defaultValue: info.value?.show === 1,
        // },
        {
          field: 'memberState',
          label: '退会',
          component: 'Switch',
          defaultValue: info.value?.memberState === 0,
        },
        {
          field: 'sort',
          label: '会员排序',
          component: 'NumberBox',
          defaultValue: info.value?.sort,
        },
        {
          field: 'integrity',
          component: 'Input',
          slot: 'integrity',
          itemProps: {
            labelPosition: 'left',
            labelWidth: '0rpx',
          },
        },
        {
          field: 'groupIdList',
          label: '设置负责人标签',
          component: 'CheckboxGroup',
          defaultValue: info.value?.groupIdList || [],
          itemProps: {
            labelPosition: 'top',
          },
          componentProps: {
            localdata: [],
          },
        },
      ];

      for (let i = 0; i < fields.length; i++) {
        const item = fields[i];
        appendSchemaByField({
          ...item,
        } as FormSchema);
      }

      const typeDataName = [
        { field: 'levelId', type: 'memberLevel' },
        { field: 'memberPostId', type: 'memberPost' },
      ];
      const typeRes = await memberTypeGetList(typeDataName.map((v) => v.type));
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(typeRes[item.type], { label: 'name', value: 'id' }),
          },
        });
      }

      let serviceRes = await memberServiceList();
      updateSchema({
        field: 'attacheUserId',
        componentProps: {
          localdata: localDataMapping(serviceRes, { label: 'userName', value: 'id' }),
        },
      });

      let groupRes = await memberGroupList();
      updateSchema({
        field: 'groupIdList',
        componentProps: {
          localdata: localDataMapping(groupRes, { label: 'name', value: 'id' }),
        },
      });
    } catch (error) {
      console.error(error);
    }
  };

  //字段change事件
  function onChange(e: OnchangeArgument) {
    console.log(e);
    if (e.field === 'memberEndTime') {
      let { joinTime } = getFieldsValue();
      let isValid = dayjs(e.val).isBefore(dayjs(joinTime)) || dayjs(e.val).isSame(dayjs(joinTime));
      if (isValid) {
        Toast('到期时间必须大于入会时间');
        setFieldsValue({ memberEndTime: '' });
      }
    }
  }

  const onSubmit = (e: IUpdateSettingInfoData) => {
    const {
      memberName,
      levelId,
      memberPostId,
      attacheUserId,
      joinTime,
      memberEndTime,
      groupIdList,
      leadingShow,
      companyShow,
      memberState,
      sort,
    } = e;
    updateSettingInfo({
      memberId: info.value?.memberId as number,
      memberName,
      levelId,
      memberPostId,
      attacheUserId,
      joinTime,
      memberEndTime,
      groupIdList,
      leadingShow: leadingShow ? 1 : 0,
      companyShow: companyShow ? 1 : 0,
      memberState: memberState ? 0 : 1,
      sort,
    }).then((res) => success(res));
  };

  const success = async (res: any) => {
    Toast('设置成功', 'none', 1500);
    updateFields();
  };

  const updateFields = async () => {
    if (!id.value) return;
    let r = await settingInfo(id.value);
    info.value = r;
    setFieldsValue({
      ...info.value,
      // show: info.value?.show === 1,
      leadingShow: info.value?.leadingShow === 1,
      companyShow: info.value?.companyShow === 1,
      memberState: info.value?.memberState === 0,
    });
  };

  onLoad<'MemberSet'>((op) => {
    id.value = op.id;
  });

  onMounted(() => {
    getSettingInfo();
  });

  const { hasShareImgConfig } = useAppStoreWithOut();

  onShareAppMessage(() => {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    return {
      path: setWxSharePath({ name: 'updateMembershipInfo' }),
      imageUrl: membershipShare?.iconUrl,
      title: membershipShare?.desc,
    };
  });
</script>

<style lang="scss" scoped>
  .container {
    padding-top: 30rpx;
    background-color: #fff;
    .integrity {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 88rpx;
      line-height: 88rpx;
      font-size: 28rpx;
      color: #333333;
      ._value {
        display: flex;
        align-items: center;
        .-num {
          position: relative;
          padding-right: 26rpx;
          height: 60rpx;
          line-height: 60rpx;
          border-right: 1rpx #dddddd solid;
        }
        .-share {
          padding: 0;
          width: 118rpx;
          height: 40rpx;
          text-align: center;
          line-height: 40rpx;
          font-size: 24rpx;
          color: #333333;
          border-radius: 10rpx;
          background-color: #ece2c7;
          margin-left: 30rpx;
        }
        .-share::after {
          border: none;
        }
      }
    }
  }
</style>
